package org.purl.net.sparql.geo;

import uk.me.jstott.jcoord.LatLng;

import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.function.FunctionBase4;

/**
 * SPARQL extension function that calculates the distance 
 * between two points.
 * 
 * The function accepts four parameters. These literal values 
 * define the two points using separate latitude and longitude 
 * values, as per the W3C Geo vocabulary
 *  
 * @author ldodds
 */
public class Distance extends FunctionBase4 {

	public NodeValue exec(NodeValue arg0, NodeValue arg1, NodeValue arg2,
			NodeValue arg3) {
		
		
		LatLng a = new LatLng(
				getDouble(arg0) ,
				getDouble(arg1) );

		LatLng b = new LatLng( getDouble(arg2), 
				getDouble(arg3));
		
		double distance = a.distance(b);
		return NodeValue.makeDouble(distance);				
	}

	private double getDouble(NodeValue value)
	{
		if (value.isDouble() )
		{
			return value.getDouble();
		}
		else
		{
			return Double.parseDouble( value.asString() );
		}
	}
}
